package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.contans.message.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.filter.AppTokenFilter;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    //关注信息表
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    //粉丝信息表
    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //检查参数
        if(dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "作者不存在");
        }
        Integer followId = null;
        ApAuthor apAuthor = apAuthorFeign.selectById(dto.getAuthorId());
        if (apAuthor != null){
           followId = apAuthor.getUserId();
        }
        if (followId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "关注人不存在");
        }else {
            ApUser apUser = AppThreadLocalUtils.getUser();
            if (apUser != null){
                if (dto.getOperation() == 0){
                    return followByUserId(apUser , followId , dto.getArticleId());
                }
                if (dto.getOperation() == 1){
                    return followCancelByUserId(apUser , followId);
                }
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //取消关注
    private ResponseResult followCancelByUserId(ApUser apUser, Integer followId) {
        ApUser apUser1 = apUserMapper.selectById(followId);
        if (apUser1 != null){
            ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
            if (apUserFollow != null){
                ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
                if (apUserFan != null){
                    apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
                }
                apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "未关注");
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "作者不存在");
        }
    }

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    //关注
    private ResponseResult followByUserId(ApUser apUser, Integer followId, Long articleId) {
        ApUser UserFollow = apUserMapper.selectById(followId);
        if (UserFollow == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "关注人不存在");
        }
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null){
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));
            if (apUserFan == null){
                apUserFan = new ApUserFan();
                apUserFan.setCreatedTime(new Date());
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldComment(true);
                apUserFan.setIsShieldLetter(true);
                apUserFanMapper.insert(apUserFan);
            }
            apUserFollow = new ApUserFollow();
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setFollowId(followId);
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setLevel((short)1);
            apUserFollow.setIsNotice(true);
            apUserFollowMapper.insert(apUserFollow);

            //需要给behavior发个消息将实体id（登录用户id），文章id，关注人id传送过去
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setArticleId(articleId);
            dto.setFollowId(followId);
            dto.setUserId(apUser.getId());
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
